package com.googlecode.particlesys;

import java.awt.Canvas;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.image.BufferStrategy;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

import com.googlecode.particlesys.objects.AbstractEmitter;

public class Simulation extends Canvas {

	private static final long serialVersionUID = 152401966720769115L;
	private static boolean displayingRadius = false;
	private BufferStrategy strategy;
	private final List<AbstractEmitter> emitters = new CopyOnWriteArrayList<AbstractEmitter>();

	Simulation(){
		super.setLocation(265, 0);
		super.setSize(749, 768);
		super.setBackground(Color.black);
	}
	
	void draw(Graphics g){
		((Graphics2D) g).setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);
		
		g.clearRect(0, 0, getWidth(), getHeight());
		
		for(AbstractEmitter e : emitters){
			e.draw(g, this);
		}
		
		g.setColor(Color.CYAN);
		g.drawString("Emitters: "+emitters.size(), 40, getHeight()-75);
		g.drawString("Particles: "+getParticleCount(), 40, getHeight()-50);
	}
	
	void init(int bufferCount){
		//Create the strategy
		super.createBufferStrategy(bufferCount);
		
		//Get the strategy
		this.strategy = super.getBufferStrategy();
	}
	
	final void redraw(){
		do {
			do {
				Graphics graphics = strategy.getDrawGraphics();
				draw(graphics);
				graphics.dispose();
			} while(strategy.contentsRestored());
			
			strategy.show();
		} while(strategy.contentsLost());
	}
	
	private int getParticleCount(){
		int i = 0;
		
		for(AbstractEmitter e : emitters){
			i += e.getParticles().size();
		}
		
		return i;
	}

	public List<AbstractEmitter> getEmitters(){
		return emitters;
	}

	public static void setDisplayingRadius(boolean displayingRadius){
		Simulation.displayingRadius = displayingRadius;
	}

	public static boolean isDisplayingRadius(){
		return displayingRadius;
	}
}